package com.piece.core.web.resolver;

import com.piece.core.framework.support.dto.UserDetailDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * Token转化UserDetails
 */
@Slf4j
public class TokenArgumentResolver implements HandlerMethodArgumentResolver {

    public TokenArgumentResolver() {
    }

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType().equals(UserDetailDTO.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) {
        UserDetailDTO user = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (null != authentication) {
            if (authentication instanceof OAuth2Authentication) {
                authentication = ((OAuth2Authentication) authentication).getUserAuthentication();
            }

            Object details = authentication.getDetails();
            if (details instanceof UserDetailDTO) {
                user = ((UserDetailDTO) details);
            }
        }
        return user;
    }
}
